using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WeatherSDK;

public static class WeatherSdkServiceCollectionExtensions
{
    /// <summary>
    /// 注入天气SDK
    /// </summary>
    /// <param name="services"></param>
    /// <param name="activeApi">启用的API名称</param>
    /// <returns></returns>
    /// <exception cref="ApplicationException"></exception>
    public static IServiceCollection AddWeatherSdk(this IServiceCollection services, string activeApi = null)
    {
        services.AddSingleton(provider =>
        {
            var configuration = provider.GetService<IConfiguration>() ?? new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

            var activeApiName = string.IsNullOrEmpty(activeApi) ? configuration[$"WeatherSDK:ActiveAPI"] : activeApi;
            IWeatherApi weatherApi = activeApiName switch
            {
                "DdcEnvChina" => new DdcEnvChinaWeatherProvider(),
                "QWeather" => new QWeatherProvider(),
                _ => throw new ApplicationException("请在appsettings.json中配置使用的接口名")
            };
            return weatherApi;
        });

        return services;
    }
}